#!/bin/bash 
set -e

TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage3}
SRC=${SRC:-/sources}

name=gcc
version=10.2.0

rm -rf $TMP
mkdir -p $TMP $LOG

tar xf $SRC/$name-$version.tar.xz -C $TMP

{ time \
   {

    cd $TMP/$name-$version

    case $(uname -m) in
      x86_64)
        sed -e '/m64=/s/lib64/lib/' \
            -i.orig gcc/config/i386/t-linux64
      ;;
    esac

    mkdir -v build
    cd       build

    ../configure --prefix=/usr            \
                 LD=ld                    \
                 --enable-languages=c,c++ \
                 --disable-multilib       \
                 --disable-bootstrap      \
                 --with-system-zlib
    make

    make install
    rm -rf /usr/lib/gcc/$(gcc -dumpmachine)/$version/include-fixed/bits/

    chown -v -R root:root \
        /usr/lib/gcc/*linux-gnu/$version/include{,-fixed}

    ln -sv ../usr/bin/cpp /lib

    install -v -dm755 /usr/lib/bfd-plugins
    ln -sfv ../../libexec/gcc/$(gcc -dumpmachine)/$version/liblto_plugin.so \
            /usr/lib/bfd-plugins/

    echo 'int main(){}' > dummy.c
    cc dummy.c -v -Wl,--verbose &> dummy.log
    readelf -l a.out | grep ': /lib'

    grep -o '/usr/lib.*/crt[1in].*succeeded' dummy.log

    grep -B4 '^ /usr/include' dummy.log

    grep 'SEARCH.*/usr/lib' dummy.log |sed 's|; |\n|g'

    grep "/lib.*/libc.so.6 " dummy.log

    grep found dummy.log

    rm -v dummy.c a.out dummy.log
    
    mkdir -pv /usr/share/gdb/auto-load/usr/lib
    mv -v /usr/lib/*gdb.py /usr/share/gdb/auto-load/usr/lib

    }
} 2>&1 | tee $name.log
    
[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
